<template>
  <div class="showImg">
    <!-- 左侧轮播显示区域 -->
    <el-carousel v-if="list[leftIndex].images.length>=1" class="haveImg" trigger="click">
      <el-carousel-item v-for="(item,index) in list[leftIndex].images" :key="index">
        <!-- <a :href="item.link"> -->
        <img :src="item.url" :alt="item.title"/>
        <!-- </a> -->
      </el-carousel-item>
    </el-carousel>
    <div v-if="list[leftIndex].images.length===0" class="image-mask">轮播图</div>
    <!-- 右侧轮播编辑区域 -->
    <div v-if="list.length && list[leftIndex].showRight">
      <div class="editRightImg">
        <!-- 头部提示区域 -->
        <header class="title">
          轮播图设置
          <div class="help-text">建议图片尺寸为750x400px，支持 jpg/png/gif 格式，大小不超过2MB</div>
        </header>
        <div class="editCon">
          <div
            v-for="(item,index) in list[leftIndex].images"
            :key="index"
            :class="rightIndex === index ? 'border' : ''"
            class="add_image"
            @click="right_click(index)"
          >
            <!-- 删除按钮 -->
            <img
              v-if="rightIndex === index"
              src="../../../../assets/settinyschool/delete.png"
              class="close"
              alt
              @click="close(index,item.id)"
            />
            <div class="image">
              <!--无图片-->
              <div v-if="!list[leftIndex].images[index].url">
                <div v-if="list[leftIndex].images[index]">+添加图片</div>
              </div>
              <!--有图片-->
              <div v-else class="showImage">
                <img :src="item.url" alt/>
              </div>
              <el-upload
                :file-list="fileList"
                :on-change="handleLogoChange"
                :http-request="uploadLogoFile"
                :limit="1"
                class="upload-demo"
                action=""
              >
                <el-button size="small" type="primary" class="uploadBtn">点击上传</el-button>
              </el-upload>
            </div>
            <div>
              <div>
                <span style="width:50px;">标题：</span>
                <el-input v-model="item.title" size="mini" style="width:130px;"/>
              </div>
              <div style="margin-top:10px;">
                <span style="width:50px;">链接：</span>
                <el-input v-model="item.link" size="mini" style="width:130px;"/>
              </div>
            </div>
          </div>
          <el-button
            icon="el-icon-circle-plus"
            class="add_ad"
            style="width:100%;margin:5px 0;"
            @click="add_ad()"
          >添加一个轮播图
          </el-button>
          <el-button
            icon="el-icon-search"
            class="add_ad"
            style="width:100%;margin:5px 0;"
            @click="dialog = true"
          >选择课程图片
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog title="选择课程" :visible.sync="dialog" width="500px">
      <el-row>
        <el-input
          v-model="teacherName"
          clearable
          placeholder="请输入课程名称或关键字"
          style="width:200px;"
          @clear="filterTable = tableData"
          @keyup.enter.native="searchTeacher"
        ></el-input>
        <el-button type="primary" @click="searchTeacher">搜 索</el-button>
      </el-row>
      <el-table
        type="selection"
        ref="multipleTable"
        :data="newTable"
        tooltip-effect="dark"
        :row-key="getRowKey"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column prop="title" label="名称"></el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page.sync="currentPage"
        :page-size="currentSize"
        :total="filterTable.length"
        style="margin-top:20px"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { upLoadFile } from '@/api/upLoadFile' // 数据接口
  import { delImage } from '@/api/system/mobile_assembly'
  import { getTenantId } from '@/utils/auth'
  import { courseList } from '@/api/user/user' // 数据接口
  export default {
    props: ['list', 'leftIndex'],
    data() {
      return {
        rightIndex: 0,
        fileList: [],
        logofile: '',
        linkTableData: [],
        dialog: false,
        teacherName: '',
        filterTable: [],
        tableData: [],
        currentPage: 1,
        currentSize: 5,
        // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
        getRowKey(row) {
          return row.id
        },
        multipleSelection: [], // 当前页选中的数据
        EduUserVo: {}
      }
    },
    computed: {
      newTable() {
        return this.filterTable.slice(
          (this.currentPage - 1) * this.currentSize,
          this.currentPage * this.currentSize
        )
      }
    },
    mounted() {
      this.restaurants = this.loadAll()
      this.getCourseListData()
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleCancel() {
        this.clearDialog()
      },
      clearDialog() {
        this.dialog = false
        this.$refs.multipleTable.clearSelection()
        this.multipleSelection = []
      },
      handleConfirm() {
        if (this.multipleSelection.length < 1) {
          this.$message.warning('请选择课程')
          return
        }
        this.list[this.leftIndex].images.push(...this.multipleSelection)
        //去重
        this.list[this.leftIndex].images = Array.from(new Set(this.list[this.leftIndex].images))
        this.list[this.leftIndex].images.map(i => {
          if (!i.url) {
            i.url = i.largePicture
          }
        })
        this.clearDialog()
      },
      // 接口获取数据
      getCourseListData() {
        this.EduUserVo.tenantId = getTenantId()
        // this.EduUserVo.categoryId = 0;
        // this.EduUserVo.limit = this.list[this.leftIndex].limit;
        // this.EduUserVo.day = this.list[this.leftIndex].recentDay;
        courseList(this.EduUserVo).then(response => {
          this.tableData = response.data.items
          this.filterTable = response.data.items
          this.total = response.data.total
        })
      },
      handleLogoChange(file) {
        this.logofile = file.raw
      },
      uploadLogoFile() {
        const fileForm = new FormData()
        fileForm.append('name', this.logofile.name)
        fileForm.append('uid', this.logofile.uid)
        fileForm.append('file', this.logofile)
        upLoadFile(fileForm).then(response => {
          this.list[this.leftIndex].images[this.rightIndex].url = response.data.url
        }).catch((e) => {
        })
      },
      right_click(index) {
        var that = this
        that.rightIndex = index
      },
      // 图片添加至list中
      add_ad() {
        this.list[this.leftIndex].images.push(
          {
            url: '',
            title: '',
            link: ''
          }
        )
      },
      // 删图片
      close(index, id) {
        console.log('id:' + id)
        if (id) {
          delImage(id).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list[this.leftIndex].images.splice(index, 1)
          })
        } else {
          this.list[this.leftIndex].images.splice(index, 1)
        }
      },
      // 图片上传
      beforeAvatarUpload(file) {
        const isImg = file.type === 'image/jpeg' || 'image/png' || 'image/gif'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isImg) {
          this.$message.error('上传头像图片只能是 JPG/PNG/GIG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isImg && isLt2M
      },
      handleChange(file, fileList) {
        this.fileList = fileList.slice(-1)
      },
      uploadSuccess(res, file, fileList) {
        this.list[this.leftIndex].images[this.rightIndex].url = URL.createObjectURL(file.raw)
      },
      loadAll() {
        return [
          { 'value': 'class NO.1', 'price': '2', 'number': '2', 'createTime': '2' }
        ]
      },
      searchTeacher() {
        // 如果有选择教师先清空多选数据
        this.$refs.multipleTable.clearSelection()
        this.multipleSelection = []
        let search = this.teacherName
        if (search) {
          this.filterTable = this.tableData.filter(function(dataNews) {
            return Object.keys(dataNews).some(function(key) {
              return ~String(dataNews[key])
                .toLowerCase()
                .indexOf(search)
            })
          })
        } else {
          this.filterTable = this.tableData
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .showImg {
    .image-mask {
      width: 100%;
      height: 100%;
      background-color: #e1e1e1;
      font-size: 26px;
      color: #919191;
      font-weight: 700;
      text-align: center;
      line-height: 194px;
    }

    .haveImg {
      position: relative;
      width: 100%;
      height: 194px;

      /deep/ .el-carousel__container {
        height: 100%;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .showImgTitle {
        position: absolute;
        width: 100%;
        left: 0;
        bottom: 0;
        height: 40px;
        line-height: 30px;
        padding: 5px 10px;
        color: #fff;
        background: rgba($color: #000, $alpha: 0.5);
      }
    }
  }

  .editRightImg {
    width: 400px;
    position: absolute;
    left: 105%;
    top: 0;
    padding: 10px;
    border: 1px solid #e1e1e1;
    background-color: #fafafa;

    .title {
      font-size: 14px;
      padding-bottom: 15px;
      margin-bottom: 15px;
      border-bottom: 1px solid #e1e1e1;

      .help-text {
        font-size: 12px;
        color: #616161;
        margin-top: 5px;
      }
    }

    .editCon {
      background-color: #fff;
      padding: 10px 5px;
      border: 1px solid #e1e1e1;
    }

    .add_image:after {
      display: block;
      clear: both;
      content: '';
      visibility: hidden;
      height: 0;
    }

    .add_image {
      position: relative;
      border: 1px solid rgba($color: #fff, $alpha: 0);
      padding: 10px;

      .close {
        position: absolute;
        top: -10px;
        right: -10px;
        width: 20px;

        img {
          width: 100%;
        }
      }

      .image {
        position: relative;
        float: left;
        height: 76px;
        width: 144px;
        margin-right: 10px;
        line-height: 76px;
        text-align: center;
        background-color: #f5f5f5;

        /deep/ .uploadBtn {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          opacity: 0;
        }

        /deep/ .el-upload-list {
          display: none;
        }
      }

      .showImage {
        height: 76px;
        width: 144px;
        text-align: center;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .add_image.border {
      border: 1px solid #408ffb;
    }
  }
</style>
